package com.fiill.audioplayer;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
 
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
 
public class CmdService extends Service {
    private static final String TAG = "BAHAL_SRV";
    private static final int PORT = 10010;
    private ServerSocket serverSocket;
    private AudioRecordManger mAudioRecordManger;
    private AudioTrackManager mAudioTrackManager;

    @Override
    public void onCreate() {
        super.onCreate();
        mAudioTrackManager = AudioTrackManager.getInstance();
        new Thread(new TcpIpAcceptThread()).start();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return Service.START_STICKY;
    }
 
    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    private class TcpIpAcceptThread implements Runnable {
        @Override
        public void run() {
            try {
                serverSocket = new ServerSocket(PORT);
                Log.i(TAG, "listen " + PORT);
                while (true) {
                    final Socket client = serverSocket.accept();
                    new Thread(new TcpIpEexecThread(client)).start();
                }
            } catch (Exception e) {
                Log.e(TAG, "Server error", e);
            }
        }
    }

    private class TcpIpEexecThread implements Runnable {
        private Socket client;

        public TcpIpEexecThread(Socket client) {
            this.client = client;
        }

        @Override
        public void run() {
            try {
                BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
                PrintWriter out = new PrintWriter(client.getOutputStream(), true);

                while (true) {
                    String msg = in.readLine();
                    if (msg == null) {
                        break;
                    }
                    CmdParser cp = new CmdParser(msg);
                    Log.i(TAG, "Received: " + msg);
                    processCmd(cp);
                }
            } catch (Exception e) {
                Log.e(TAG, "Client error", e);
            } finally {
                try {
                    client.close();
                } catch (Exception e) {
                    // ignore on close
                }
            }
        }
    }

    void processCmd(CmdParser cp) {
        if(cp.cmd.equals("PLAY")) {
            mAudioTrackManager.startPlay(cp.url, cp.audioContext, cp.channelMask, cp.bitFormat);
        } else if (cp.cmd.equals("STOP")){
            mAudioTrackManager.stopPlay();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            if (serverSocket != null) {
                serverSocket.close();
            }
        } catch (Exception e) {
            Log.e(TAG, "Socket close error", e);
        }
    }

    class CmdParser {
        public String cmd = "";
        public String url = "";
        public String audioContext = "";
        public String channelMask = "";
        public String bitFormat = "";

        CmdParser(String parseStr) {
            stringSplite(parseStr);
        }

        void stringSplite(String input) {
            String[] lines = input.split(" ");
            for (String line : lines) {
              String[] parts = line.split(":"); 
              if (parts.length == 2) {
                try {
                    String value = parts[1].trim();
                    if(null == value) value = "";
                    if (parts[0].equals("CMD")) cmd = value;
                    if (parts[0].equals("URL")) url = value;
                    if (parts[0].equals("AUDIOCONTEXT")) audioContext = value;
                    if (parts[0].equals("CHANNELMASK")) channelMask = value;
                    if (parts[0].equals("BITFORMAT")) bitFormat = value;
                } catch (NumberFormatException e) {
                    Log.e(TAG, "Invalid value: " + parts[1]);
                }
              }
            }
        }
    }
}